package argo.review;

import argo.hot100.linklist.ListNode;

import java.util.List;

/**
 * 翻转链表区间
 */
public class ReverseBetweenLinkList {

    public ListNode reverseBetween(ListNode head, int left, int right) {

        if (left == right) {
            return head;
        }
        ListNode startPre = null, start, p = head, end, endNxt, dumHead = new ListNode(-1);
        dumHead.next = head;
        int i = 1;
        while (i < left) {
            startPre = p;
            p = p.next;
            i++;
        }
        start = p;

        while (i < right) {
            p = p.next;
            i++;
        }
        end = p;
        endNxt = p.next;

        reverse(start, end);

        //process start
        if (startPre != null) {
            startPre.next = end;
        } else {
            dumHead.next = end;
        }

        //process end
        if (endNxt != null) {
            start.next = endNxt;
        }


        return dumHead.next;

    }

    public ListNode reverse(ListNode head, ListNode tail) {

        ListNode pre = null, cur = head, nxt;
        do {
            nxt = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nxt;

        } while (cur != tail);
        tail.next = pre;
        return tail;
    }


    public ListNode createList(int[] nums) {
        ListNode p = new ListNode(-1), dumy = p;


        for (int num : nums) {
            p.next = new ListNode(num);
            p = p.next;
        }
        return dumy.next;

    }

    public void traverList(ListNode list) {
        while (list != null) {
            System.out.println(list.val);
            list = list.next;
        }
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1, 2, 3, 4, 5};
        ReverseBetweenLinkList rev = new ReverseBetweenLinkList();
        ListNode list = rev.createList(nums);
        ListNode listNode = rev.reverseBetween(list, 2, 4);

        rev.traverList(listNode);

    }


}
